package myky.com.doctorapp.ui

import android.app.Activity
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.PopupWindow
import com.blankj.utilcode.util.KeyboardUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.nukc.stateview.Constant
import com.gyf.barlibrary.ImmersionBar
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.android.synthetic.main.activity_doctor_list.*
import myky.com.doctorapp.R
import myky.com.doctorapp.adapter.*
import myky.com.doctorapp.base.BaseActivity
import myky.com.doctorapp.base.CMApplication
import myky.com.doctorapp.contract.DoctorListContract
import myky.com.doctorapp.entity.DepatmentAndAreaEntity
import myky.com.doctorapp.entity.DoctorWrapperEntity
import myky.com.doctorapp.entity.PageEntity
import myky.com.doctorapp.presenter.DoctorListPresenter
import myky.com.doctorapp.utils.Constants
import myky.com.doctorapp.utils.ToastUtils


/**
 * Title:医生列表
 * Description: TODO
 * @author xiangyao
 * date 2019/1/15
 */
class DoctorListActivity : BaseActivity<DoctorListPresenter, DoctorWrapperEntity.DoctorListEntity.DoctorsEntity>(), DoctorListContract.View, OnRefreshLoadMoreListener, View.OnClickListener, BaseQuickAdapter.OnItemChildClickListener {

    var currentSelectDepartmentPostion = 0
    var currentSelectDepartmentCHPostion = 0
    var currentSelectDepartmentName: String = "全部科室"
    var currentSelectProvincePostion: Int = 0
    var currentSelectCityPostion: Int = 0
    var currentProvinceName: String = "全部地区"
    var currentCityName: String = "全部地区"
    var currentDeapartName: String = "全部科室"
    var currentPage: Int = 1
    lateinit var areaPopupWindow: PopupWindow
    lateinit var departmentPopupWindow: PopupWindow
    lateinit var mAreaPronviceList: MutableList<DepatmentAndAreaEntity.DataEntity.AreaEntity>
    lateinit var mAreaCityList: MutableList<DepatmentAndAreaEntity.DataEntity.AreaEntity.CityEntity>
    lateinit var mAreaProvinceAdapter: DoctorLisProvinceAdapter
    lateinit var mAreaCityAdapter: DoctorListCityAdapter
    lateinit var doc_province_listview: RecyclerView
    lateinit var doc_city_listview: RecyclerView
    lateinit var departmentListView: RecyclerView
    lateinit var departmentChildListView: RecyclerView
    lateinit var mDeapartMentList: MutableList<DepatmentAndAreaEntity.DataEntity.DepartmentEntity>
    lateinit var mDeapartMentChirldList: MutableList<DepatmentAndAreaEntity.DataEntity.DepartmentEntity.DepartmentchildEntity>
    lateinit var mDeapartmentAdapter: DoctorLisDepartmentAdapter
    lateinit var mDeapartmenChildAdapter: DoctorLisDepartmentCHAdapter
    private var now_current = 1
    private var page = 1
    private lateinit var doctorAdapter: DoctorListDoctorAdapter
    private lateinit var mDoctorList: MutableList<DoctorWrapperEntity.DoctorListEntity.DoctorsEntity>
    var receviewKeyWord = ""


    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        when (view?.id) {

            R.id.ll_doctor_details_top -> {

                val data = doctorAdapter.data

                val doctorsEntity = data[position]
                val bundle = Bundle()
                bundle.putInt(Constants.DOCTORID,Integer.parseInt(doctorsEntity.doctorid))
                startActivity(DoctorDetailsActivity::class.java, bundle)

            }
            R.id.department_layout -> {
                currentSelectDepartmentPostion = position
                val data = mDeapartmentAdapter.data
                val department = data[position]
                currentSelectDepartmentName = department.departmentname
                val deparmentCh = department.departmentchild
                mDeapartmentAdapter.setDepartMent(department.departmentname)
                mDeapartMentChirldList.clear()
                mDeapartMentChirldList.addAll(deparmentCh)
                mDeapartmentAdapter.notifyDataSetChanged()
                mDeapartmenChildAdapter.notifyDataSetChanged()
            }
            R.id.doc_province_lisrview_item -> {
                currentSelectProvincePostion = position
                val data = mAreaProvinceAdapter.data
                val province = data[position]
                currentProvinceName = province.province
                val city = province.city
                mAreaProvinceAdapter.setProvince(province.province)
                mAreaCityList.clear()
                mAreaCityList.addAll(city)
                mAreaProvinceAdapter.notifyDataSetChanged()
                mAreaCityAdapter.notifyDataSetChanged()
            }
            R.id.departmentChildLlayout -> {
                currentSelectDepartmentCHPostion = position
                currentPage = 1
                val data = mDeapartmenChildAdapter.data
                val departmentChildName = data[position].departmentchildname
                departmentTextView.text = departmentChildName
                mDeapartmenChildAdapter.setDepartmentCHA(departmentChildName)
                mDeapartmenChildAdapter.notifyDataSetChanged()
                currentDeapartName = departmentChildName
                mDoctorList.clear()
                mPresenter.findDoctorList(Constants.CURRENTVERSION, mUserId.toString(), 10,
                        currentPage, "2", 0, "", currentProvinceName,
                        currentCityName, currentDeapartName
                )
                departmentPopupWindow.dismiss()
            }
            R.id.doc_city_lisrview_item -> {
                currentPage = 1
                currentSelectCityPostion = position
                val data = mAreaCityAdapter.data
                val cityName = data[position].cityName
                areaTextView.text = cityName
                mAreaCityAdapter.setCity(cityName)
                mAreaCityAdapter.notifyDataSetChanged()
                currentCityName = cityName
                mDoctorList.clear()
                mPresenter.findDoctorList(Constants.CURRENTVERSION, mUserId.toString(), 10,
                        currentPage, "2", 0, "", currentProvinceName,
                        currentCityName, currentDeapartName
                )
                areaPopupWindow.dismiss()
            }

            R.id.item_smallbtn_consoult -> {

                val loginOk = CMApplication.get().isLoginOk

                if (loginOk) {
                    val data = doctorAdapter.data

                    val doctorsEntity = data[position]
                    val bundle = Bundle()
                    bundle.putInt(Constants.DOCTORID,Integer.parseInt(doctorsEntity.doctorid))
                    startActivity(ExpertConsultActivity::class.java, bundle)
                } else {
                    startActivity(LoginActivity::class.java)
                }


            }
            R.id.item_smallbtn_remote -> {
                ToastUtils.show("远程问诊")

            }
            R.id.item_smallbtn_bespeak -> {
                ToastUtils.show("预约门诊")

            }
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.areaPop -> {
                val showing = departmentPopupWindow.isShowing
                if (showing) {
                    departmentPopupWindow.dismiss()
                }
                doc_province_listview.smoothScrollToPosition(currentSelectProvincePostion)
                doc_city_listview.smoothScrollToPosition(currentSelectCityPostion)
                areaTextView.setTextColor(resources.getColor(R.color.theme_app))
                showPopWindow(areaPopupWindow, new_doctor_list_screen)
            }
            R.id.departmentPop -> {
                val showing = areaPopupWindow.isShowing
                if (showing) {
                    areaPopupWindow.dismiss()
                }
                departmentListView.smoothScrollToPosition(currentSelectProvincePostion)
                departmentChildListView.smoothScrollToPosition(currentSelectCityPostion)
                departmentTextView.setTextColor(resources.getColor(R.color.theme_app))
                showPopWindow(departmentPopupWindow, new_doctor_list_screen)
            }
        }
    }

    override fun showDeapartmentAndArea(depatmentAndAreaEntity: DepatmentAndAreaEntity.DataEntity) {
        val area = depatmentAndAreaEntity.area
        val department = depatmentAndAreaEntity.department
        initPopWindows(area, department)
    }


    private fun initPopWindows(area: List<DepatmentAndAreaEntity.DataEntity.AreaEntity>, department: List<DepatmentAndAreaEntity.DataEntity.DepartmentEntity>) {
        initAreaPopWindow(area)
        initDeapartmentPopWindow(department)
    }

    private fun initDeapartmentPopWindow(department: List<DepatmentAndAreaEntity.DataEntity.DepartmentEntity>) {
        mDeapartMentList = ArrayList()
        mDeapartMentChirldList = ArrayList()
        val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val view = inflater.inflate(R.layout.pop_doctor_deparment, null)
        departmentListView = view.findViewById<View>(R.id.doc_department_lisrview) as RecyclerView
        departmentChildListView = view.findViewById<View>(R.id.doc_departmentChild_lisrview) as RecyclerView
        departmentListView.layoutManager = LinearLayoutManager(this)
        departmentChildListView.layoutManager = LinearLayoutManager(this)
        mDeapartMentList.addAll(department)
        mDeapartMentChirldList.addAll(department[0].departmentchild)
        mDeapartmentAdapter = DoctorLisDepartmentAdapter(mDeapartMentList)
        mDeapartmenChildAdapter = DoctorLisDepartmentCHAdapter(mDeapartMentChirldList)
        departmentListView.adapter = mDeapartmentAdapter
        departmentChildListView.adapter = mDeapartmenChildAdapter
        mDeapartmentAdapter.onItemChildClickListener = this
        mDeapartmenChildAdapter.onItemChildClickListener = this

        val wm = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val width = wm.defaultDisplay.width
        val height = wm.defaultDisplay.height
        departmentPopupWindow = PopupWindow(view, width, height, false)
        departmentPopupWindow.setBackgroundDrawable(BitmapDrawable())
        departmentPopupWindow.animationStyle = R.style.anim_menu_topbar
        departmentPopupWindow.isFocusable = false
        departmentPopupWindow.isOutsideTouchable = false
        view.findViewById<View>(R.id.emptyLayout).setOnClickListener { departmentPopupWindow.dismiss() }
        departmentPopupWindow.setOnDismissListener { departmentTextView.setTextColor(resources.getColor(R.color.black_333333)) }

    }

    /**
     * 初始化地区筛选popwindow
     *
     * @param area  地区集合
     * */
    private fun initAreaPopWindow(area: List<DepatmentAndAreaEntity.DataEntity.AreaEntity>) {

        mAreaPronviceList = ArrayList()

        mAreaCityList = ArrayList()

        val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

        val view = inflater.inflate(R.layout.pop_doctor_list_screen, null)

        doc_province_listview = view.findViewById<View>(R.id.doc_province_lisrview) as RecyclerView

        doc_city_listview = view.findViewById<View>(R.id.doc_city_lisrview) as RecyclerView

        doc_province_listview.layoutManager = LinearLayoutManager(this)

        doc_city_listview.layoutManager = LinearLayoutManager(this)

        mAreaPronviceList.addAll(area)

        mAreaCityList.addAll(area[0].city)

        mAreaProvinceAdapter = DoctorLisProvinceAdapter(mAreaPronviceList)

        mAreaCityAdapter = DoctorListCityAdapter(mAreaCityList)

        doc_province_listview.adapter = mAreaProvinceAdapter

        doc_city_listview.adapter = mAreaCityAdapter

        mAreaProvinceAdapter.onItemChildClickListener = this

        mAreaCityAdapter.onItemChildClickListener = this


        val wm = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val width = wm.defaultDisplay.width
        val height = wm.defaultDisplay.height
        areaPopupWindow = PopupWindow(view, width, height, false)
        areaPopupWindow.setBackgroundDrawable(BitmapDrawable())
        areaPopupWindow.animationStyle = R.style.anim_menu_topbar
        areaPopupWindow.isFocusable = false
        areaPopupWindow.isOutsideTouchable = false
        view.findViewById<View>(R.id.emptyLayout).setOnClickListener { areaPopupWindow.dismiss() }

        areaPopupWindow.setOnDismissListener { areaTextView.setTextColor(resources.getColor(R.color.black_333333)) }

    }


    override fun reloadActivity() {
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {

        if (now_current >= page) {
            refreshLayout.finishRefresh()
            refreshLayout.finishLoadMore()
            refreshLayout.setEnableLoadMore(false)
            ToastUtils.show("已经是最后一页了")
        } else {
            now_current++
            mPresenter.findDoctorList(Constants.CURRENTVERSION, "0", 10, now_current, "2", 0, receviewKeyWord, currentProvinceName, currentCityName, currentDeapartName)
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        now_current = 1
        mDoctorList.clear()
        doctorAdapter.notifyDataSetChanged()
        mPresenter.findDoctorList(Constants.CURRENTVERSION, "0", 10, now_current, "2", 0, receviewKeyWord, currentProvinceName, currentCityName, currentDeapartName)
    }

    override fun injectTarget(): View = findViewById(R.id.new_doctor_list_refresh)

    override fun initData() {

        mPresenter.findDoctorList(Constants.CURRENTVERSION, "0", 10, 1, "2", 0, receviewKeyWord, currentProvinceName, currentCityName, currentDeapartName)

        mPresenter.findDeapartmentAndArea("v1.0")

    }


    /**
     *初始化搜索框的文字，并匹配搜索
     * */
    override fun initView() {
        ImmersionBar.with(this).keyboardEnable(true).fitsSystemWindows(true)
                .statusBarColor(R.color.white).statusBarDarkFont(true, 0.2f).init()

        mDoctorList = ArrayList()
        new_doctor_list_recycler.layoutManager = LinearLayoutManager(this)
        doctorAdapter = DoctorListDoctorAdapter(mDoctorList, inputEditText.text.toString())
        new_doctor_list_recycler.adapter = doctorAdapter
        new_doctor_list_refresh.setOnRefreshLoadMoreListener(this)

        areaPop.setOnClickListener(this)

        departmentPop.setOnClickListener(this)

        doctorAdapter.onItemChildClickListener = this

        inputEditText.setOnClickListener {
            areaPopupWindow.dismiss()
            departmentPopupWindow.dismiss()
        }


        val extras = intent.extras
        if (extras != null) {

            receviewKeyWord = extras.getString(Constant.COMOONBUNDLEKEY)

            if (!TextUtils.isEmpty(receviewKeyWord)) {
                inputEditText.setText(receviewKeyWord)
            }
        }




        cleanLayout.setOnClickListener { inputEditText.setText("") }


        new_doctor_list_recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {

                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    KeyboardUtils.hideSoftInput(this@DoctorListActivity)
                }
            }

        })




        inputEditText.setOnEditorActionListener { textView, i, _ ->
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                KeyboardUtils.hideSoftInput(this)
                mDoctorList.clear()

                if (!TextUtils.isEmpty(inputEditText.text.toString())) {
                    val s = inputEditText.text.toString()
                    doctorAdapter.setKeyWord(s)
                }

                mPresenter.findDoctorList(Constants.CURRENTVERSION, mUserId.toString(), 10,
                        currentPage, "2", 0, inputEditText.text.toString(), currentProvinceName,
                        currentCityName, currentDeapartName)

                return@setOnEditorActionListener true

            }

            return@setOnEditorActionListener false
        }


    }

    override fun getContenView(): Int = R.layout.activity_doctor_list

    override fun showDataSuccess(datas: DoctorWrapperEntity.DoctorListEntity.DoctorsEntity?) {
    }

    override fun showDoctorList(doctoerList: MutableList<DoctorWrapperEntity.DoctorListEntity.DoctorsEntity>, pageEntity: PageEntity) {
        doctorAdapter.removeAllHeaderView()
        page = pageEntity.pages
        mDoctorList.addAll(doctoerList)
        doctorAdapter.notifyDataSetChanged()
        doctorAdapter.loadMoreComplete()
        new_doctor_list_refresh.finishRefresh()
        new_doctor_list_refresh.finishLoadMore()

    }

    override fun showDefaultDoctor(doctoerList: MutableList<DoctorWrapperEntity.DoctorListEntity.DoctorsEntity>, pageEntity: PageEntity) {
        val headerView = LayoutInflater.from(this).inflate(R.layout.doc_header, null, false)
        doctorAdapter.setHeaderView(headerView)
        page = pageEntity.pages
        mDoctorList.addAll(doctoerList)
        doctorAdapter.notifyDataSetChanged()
        doctorAdapter.loadMoreComplete()

        new_doctor_list_refresh.finishRefresh()
        new_doctor_list_refresh.finishLoadMore()

        new_doctor_list_recycler.smoothScrollToPosition(0)
    }

    override fun getPresenter(): DoctorListPresenter = DoctorListPresenter()


    //适配目前所有机型PopWidow展示
    protected fun showPopWindow(popupwindow: PopupWindow, view: View) {
        // 系统7.0以上， popupwindow底层修改了Gravity属性 Gravity.START
        // | Gravity.TOP
        val a = IntArray(2)
        view.getLocationOnScreen(a)
        //【note!】Gets the screen height without the virtual key
        val wmm = getSystemService(Activity.WINDOW_SERVICE) as WindowManager
        val screenHeight = wmm.defaultDisplay.height
        /*
         * PopupWindow height for match_parent,
         * will occupy the entire screen, it needs to do special treatment in Android 7.1
         */
        popupwindow.height = screenHeight - a[1] - view.height
        popupwindow.showAtLocation(view,
                Gravity.NO_GRAVITY, 0, a[1] + view.height)
    }
}
